package com.wochoose.jojo.ucm.component.aop;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
@Order(1)
public class LogAspect {

    @Around("execution(* com.wochoose.jojo.ucm.biz.web..*.*(..))")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        MDC.put("log_uid", UUID.randomUUID().toString().replace("-", ""));
        String method = joinPoint.getSignature().getName();
        log.info("====== 开始执行{}.{}", joinPoint.getTarget().getClass(), method);

        Object result = null;

        Object[] args = joinPoint.getArgs();
        List<Object> arguments  = new ArrayList<>();
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                continue;
            }
            arguments.add(args[i]);
        }
        String paramter = "";
        if (CollectionUtil.isNotEmpty(arguments)) {
            try {
                paramter = JSONUtil.toJsonStr(arguments);
            } catch (Exception e) {
                paramter = arguments.toString();
            }
        }
        log.info("====== 请求参数 {}", paramter);

        result = joinPoint.proceed();

        log.info("====== 请求返回  {} ======", JSONUtil.toJsonStr(result));
        MDC.clear();
        return result;
    }


    public static void responseJson(HttpServletResponse response, Object obj){
        response.setContentType("application/json; charset=utf-8");
        try(PrintWriter writer = response.getWriter()){
            writer.print(JSONUtil.toJsonStr(obj));
            response.flushBuffer();
        }catch(Exception e){
            log.info("response写入数据异常", e);
        }
    }
}